import 'element-ui/lib/theme-chalk/index.css';

import Vue from 'vue';

import axios from 'axios';
import ElementUI, { Message } from 'element-ui';
import { VueMasonryPlugin } from 'vue-masonry';

import App from './App.vue';
import router from './router';
import store from './store/store';

Vue.config.productionTip = false
Vue.prototype.$axios= axios
Vue.use(ElementUI);
Vue.use(VueMasonryPlugin);


// axios.interceptors.request.use(
//   config => {
//     var token = localStorage.getItem('isLoginSuccess')
//       if (token) {
//           config.headers['Authorization'] ='Bearer ' + token;
//       }
//       return config
//   },
//   error => {
//       return Promise.reject(error)
//   }
//   );
  axios.interceptors.response.use(res => {
    // 成功响应的拦截
    return Promise.resolve(res)
  }, err =>{
    // 失败响应的拦截
    if(err.response){
      // 失败响应的status需要在response中获得
      console.error(err.response.data.message)
      switch(err.response.status){
        // 对得到的状态码的处理，具体的设置视自己的情况而定
        case 401:
          localStorage.removeItem('isLoginSuccess')
          store.commit('changeState')
          Message({
            type: 'error',
            message: '身份已过期，请重新登录',
            duration: 2000
          });
           router.push('/login')
          break;
        // case 422 :
        //   Message({
        //     type: 'error',
        //     message: err.response.data.message,
        //     duration: 2000
        //   });  
        //   break;
          default :
          Message({
            type: 'error',
            message: err.response.data.message,
            duration: 2000
          });
          break;
      }
    }
    return Promise.reject(err)
  })

// 登录路由拦截
router.beforeEach((to,from,next)=>{
  let require = to.matched.some((item)=>{return item.meta.loginRequired})
  if(require){//需要登录权限
     if(store.state.isLoginSuccess){//已经登录
        next()
     }else{//未登录
         next({
           path:'/'
         })
     }
  }else{
    next()
  }
})
router.afterEach(()=>{
window.scrollTo(0,0)
})
new Vue({
  render: h => h(App),
  router,
  store,
}).$mount('#app')
